package com.shuda.business.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.crm.entity.CustomerStatusHistoryEntity;
import com.shuda.business.crm.mapper.CustomerStatusHistoryMapper;
import com.shuda.business.crm.service.CustomerStatusHistoryService;
import com.shuda.common.core.domain.PageDTO;
import com.shuda.common.core.domain.PageResult;
import com.shuda.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户状态历史记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerStatusHistoryServiceImpl extends ServiceImpl<CustomerStatusHistoryMapper, CustomerStatusHistoryEntity> 
        implements CustomerStatusHistoryService {

    private final CustomerStatusHistoryMapper customerStatusHistoryMapper;

    @Override
    public PageResult<CustomerStatusHistoryEntity> getCustomerStatusHistoryPage(PageDTO pageDTO, Long customerId) {
        return getStatusHistoryByCustomerId(pageDTO, customerId);
    }

    @Override
    @Transactional
    public CustomerStatusHistoryEntity createCustomerStatusHistory(CustomerStatusHistoryEntity historyEntity) {
        historyEntity.setCreateBy(SecurityUtils.getCurrentUsername());
        historyEntity.setCreateTime(LocalDateTime.now());
        historyEntity.setDeleted(0);
        
        this.save(historyEntity);
        return historyEntity;
    }

    @Override
    public PageResult<CustomerStatusHistoryEntity> getStatusHistoryByCustomerId(PageDTO pageDTO, Long customerId) {
        LambdaQueryWrapper<CustomerStatusHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerStatusHistoryEntity::getCustomerId, customerId)
               .eq(CustomerStatusHistoryEntity::getDeleted, 0)
               .orderByDesc(CustomerStatusHistoryEntity::getCreateTime);
        
        IPage<CustomerStatusHistoryEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        IPage<CustomerStatusHistoryEntity> resultPage = this.page(page, wrapper);
        
        return new PageResult<>(
            resultPage.getRecords(),
            resultPage.getTotal(),
            resultPage.getCurrent(),
            resultPage.getSize()
        );
    }
}